import { Content, ContentType } from '../../types/document';
import { SearchFilters } from './types';

export class FilterProcessor {
  /**
   * 应用筛选条件
   */
  async applyFilters(documents: Content[], filters: SearchFilters): Promise<Content[]> {
    let filtered = [...documents];

    // 按内容类型筛选
    if (filters.contentType && filters.contentType.length > 0) {
      filtered = filtered.filter(doc => filters.contentType!.includes(doc.type));
    }

    // 按时间范围筛选
    if (filters.dateRange) {
      const { start, end } = filters.dateRange;
      filtered = filtered.filter(doc => 
        doc.createdAt >= start && doc.createdAt <= end
      );
    }

    // 按文档大小筛选
    if (filters.minSize !== undefined || filters.maxSize !== undefined) {
      filtered = filtered.filter(doc => {
        const size = this.calculateDocumentSize(doc);
        
        if (filters.minSize !== undefined && size < filters.minSize) {
          return false;
        }
        
        if (filters.maxSize !== undefined && size > filters.maxSize) {
          return false;
        }
        
        return true;
      });
    }

    // 按标签筛选（暂时跳过，等标签系统实现后添加）
    if (filters.tags && filters.tags.length > 0) {
      // TODO: 实现标签筛选逻辑
      console.log('[FilterProcessor] 标签筛选功能待实现');
    }

    // 按附件状态筛选
    if (filters.hasAttachments !== undefined) {
      filtered = filtered.filter(doc => {
        const hasAttachments = this.documentHasAttachments(doc);
        return hasAttachments === filters.hasAttachments;
      });
    }

    console.log(`[FilterProcessor] 筛选完成: ${documents.length} -> ${filtered.length}`);
    return filtered;
  }

  /**
   * 计算文档大小（字符数）
   */
  private calculateDocumentSize(document: Content): number {
    let size = document.title.length;

    switch (document.type) {
      case ContentType.TEXT_DOCUMENT:
        size += (document.data.content || '').length;
        break;
      default:
        break;
    }

    return size;
  }

  /**
   * 检查文档是否有附件
   */
  private documentHasAttachments(document: Content): boolean {
    // 暂时返回false，后续根据实际附件系统实现
    return false;
  }

  /**
   * 验证筛选条件
   */
  validateFilters(filters: SearchFilters): string | null {
    // 验证时间范围
    if (filters.dateRange) {
      const { start, end } = filters.dateRange;
      if (start > end) {
        return '开始时间不能晚于结束时间';
      }
      
      const now = Date.now();
      if (start > now || end > now) {
        return '时间范围不能超过当前时间';
      }
    }

    // 验证大小范围
    if (filters.minSize !== undefined && filters.minSize < 0) {
      return '最小大小不能为负数';
    }
    
    if (filters.maxSize !== undefined && filters.maxSize < 0) {
      return '最大大小不能为负数';
    }
    
    if (filters.minSize !== undefined && filters.maxSize !== undefined) {
      if (filters.minSize > filters.maxSize) {
        return '最小大小不能大于最大大小';
      }
    }

    // 验证内容类型
    if (filters.contentType && filters.contentType.length > 0) {
      const validTypes = Object.values(ContentType);
      const invalidTypes = filters.contentType.filter(type => !validTypes.includes(type));
      if (invalidTypes.length > 0) {
        return `无效的内容类型: ${invalidTypes.join(', ')}`;
      }
    }

    return null;
  }

  /**
   * 获取筛选条件的描述文本
   */
  getFiltersDescription(filters: SearchFilters): string {
    const descriptions: string[] = [];

    if (filters.contentType && filters.contentType.length > 0) {
      const typeNames = filters.contentType.map(type => this.getContentTypeName(type));
      descriptions.push(`类型: ${typeNames.join(', ')}`);
    }

    if (filters.dateRange) {
      const startDate = new Date(filters.dateRange.start).toLocaleDateString();
      const endDate = new Date(filters.dateRange.end).toLocaleDateString();
      descriptions.push(`时间: ${startDate} 至 ${endDate}`);
    }

    if (filters.minSize !== undefined || filters.maxSize !== undefined) {
      let sizeDesc = '大小: ';
      if (filters.minSize !== undefined && filters.maxSize !== undefined) {
        sizeDesc += `${filters.minSize} - ${filters.maxSize} 字符`;
      } else if (filters.minSize !== undefined) {
        sizeDesc += `≥ ${filters.minSize} 字符`;
      } else if (filters.maxSize !== undefined) {
        sizeDesc += `≤ ${filters.maxSize} 字符`;
      }
      descriptions.push(sizeDesc);
    }

    if (filters.tags && filters.tags.length > 0) {
      descriptions.push(`标签: ${filters.tags.length} 个`);
    }

    if (filters.hasAttachments !== undefined) {
      descriptions.push(filters.hasAttachments ? '有附件' : '无附件');
    }

    return descriptions.length > 0 ? descriptions.join(', ') : '无筛选条件';
  }

  /**
   * 获取内容类型的中文名称
   */
  private getContentTypeName(type: ContentType): string {
    switch (type) {
      case ContentType.TEXT_DOCUMENT:
        return '文本文档';
      case ContentType.STORYBOARD:
        return '分镜脚本';
      case ContentType.DATA_COLLECTION:
        return '数据采集';
      default:
        return '未知类型';
    }
  }

  /**
   * 创建空的筛选条件
   */
  static createEmptyFilters(): SearchFilters {
    return {};
  }

  /**
   * 复制筛选条件
   */
  static cloneFilters(filters: SearchFilters): SearchFilters {
    return {
      contentType: filters.contentType ? [...filters.contentType] : undefined,
      dateRange: filters.dateRange ? { ...filters.dateRange } : undefined,
      tags: filters.tags ? [...filters.tags] : undefined,
      minSize: filters.minSize,
      maxSize: filters.maxSize,
      hasAttachments: filters.hasAttachments
    };
  }

  /**
   * 检查筛选条件是否为空
   */
  static isEmptyFilters(filters: SearchFilters): boolean {
    return (
      (!filters.contentType || filters.contentType.length === 0) &&
      !filters.dateRange &&
      (!filters.tags || filters.tags.length === 0) &&
      filters.minSize === undefined &&
      filters.maxSize === undefined &&
      filters.hasAttachments === undefined
    );
  }

  /**
   * 合并筛选条件
   */
  static mergeFilters(base: SearchFilters, override: SearchFilters): SearchFilters {
    return {
      contentType: override.contentType ?? base.contentType,
      dateRange: override.dateRange ?? base.dateRange,
      tags: override.tags ?? base.tags,
      minSize: override.minSize ?? base.minSize,
      maxSize: override.maxSize ?? base.maxSize,
      hasAttachments: override.hasAttachments ?? base.hasAttachments
    };
  }
}